package com.wsch.client.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 讀取json工具類, new WtcJsonMap(json.toMap())創建jsonmap對象
 * 
 * @author macpl
 *
 */
public class WtcJsonMap {
	private Map<String, Object> data;

	public WtcJsonMap(Map<String, Object> map) {
		data = map;
	}

	public String getString(String... keys) {
		if (getObject(keys) == null) {
			return " ";
		}
		return getObject(keys).toString();
	}

	@SuppressWarnings("unchecked")
	public Object getObject(String... keys) {
		Object curentObj = null;
		for (String key : keys) {
			if (curentObj == null) {
				curentObj = data.get(key);
			} else {
				curentObj = ((Map<String, Object>) curentObj).get(key);
			}
		}
		return curentObj;
	}

	public int getInt(String... keys) {
		if (getObject(keys) == null) {
			return 0;
		}
		return Integer.valueOf(getObject(keys).toString());
	}

	public Float getFloat(String... keys) {
		if (getObject(keys) == null) {
			return new Float(0);
		}
		return Float.valueOf(getObject(keys).toString());
	}

	public long getLong(String... keys) {
		if (getObject(keys) == null) {
			return new Long(0);
		}
		return Long.valueOf(getObject(keys).toString());
	}

	@SuppressWarnings("unchecked")
	public List<WtcJsonMap> getList(String... keys) {
		List<WtcJsonMap> list = new ArrayList<WtcJsonMap>();
		Object obj = getObject(keys);
		if (obj == null) {
			return new ArrayList<WtcJsonMap>();
		}
		for (Map<String, Object> node : (List<Map<String, Object>>) obj) {
			list.add(new WtcJsonMap(node));
		}
		return list;
	}

	public Object getValue() {
		for (Map.Entry<String, Object> node : data.entrySet()) {
			return node.getValue();
		}
		return null;
	}

	public int getIntValue() {
		Object val = getValue();
		if (val != null) {
			return Integer.valueOf(val.toString());
		} else {
			return 0;
		}
	}

	public boolean has(String... keys) {
		return getObject(keys) != null;
	}
}
